import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/model/group_details_entity.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/chat_window/chat_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/address_book/address_list_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/chat_history/chat_record_view.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:get/get.dart';

import 'chats_setting_logic.dart';
import '../../util/rong_widget.dart';
import 'group_code_page.dart';
import 'group_user_view.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/15 11:10
/// filePath： lib/page/rong_im/chats_setting_view.dart
/// desc: 群聊 对话设置
/// <summary>
///
class ChatsSettingPage extends StatefulWidget {
  final int groupType ; // 1群主  2成员
  final String groupId;  // 群id
  ChatsSettingPage({required this.groupType,required this.groupId});
  @override
  _ChatsSettingPageState createState() => _ChatsSettingPageState();
}

class _ChatsSettingPageState extends State<ChatsSettingPage> {
  final logic = Get.put(ChatsSettingLogic());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    logic.getData(widget.groupId);
  }
  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChatsSettingLogic>(
      builder: (controller) {
        // 一行5个
        double imgWh = (Get.width - 90) / 5;
        return Scaffold(
          appBar: RongWidget.appBarWidget(title: "${logic.groupDetailsData.groupName} (${logic.groupDetailsData.groupCount})"),
          body:  logic.groupDetailsData.users == null ? SizedBox():ListView(
            padding: EdgeInsets.all(0),
            children: [
              Container(
                width: Get.width,
                color: Colors.grey.shade100,
                padding: EdgeInsets.all(15),
                child: Wrap(
                  runSpacing: 15,
                  spacing: 15,
                  children: [
                    ...List.generate(logic.groupDetailsData.users!.length, (index){
                      return Container(
                        width: imgWh,
                        height: imgWh,
                        child: RongWidget.imgNet("${logic.groupDetailsData.users![index].picUrl}",onTap: (){
                          Get.to(()=>ChatPage(
                            conversationType: 1,
                            targetId: logic.groupDetailsData.users![index].ryUserId!,
                            title:logic.groupDetailsData.users![index].remarkName,
                            userPic: logic.groupDetailsData.users![index].picUrl,
                            friendId: logic.groupDetailsData.users![index].userId,
                          ));
                        },borderRadius: BorderRadius.circular(10)),
                      );
                    })
                  ]..add(
                      Container(
                        width: imgWh,
                        height: imgWh,
                        child: RongWidget.imgAsset("add_f.png",onTap: (){
                          print("拉人");
                          Get.to(()=>AddressListPage(type: 1,))!.then((value) async{
                            print(value);
                            if(value!=null){
                              logic.addGroup(value);
                            }
                          });
                        }),
                      ),// 群主才有踢人
                  )..add(widget.groupType == 1 ? Container(
                    width: imgWh,
                    height: imgWh,
                    child: RongWidget.imgAsset("rem_f.png",onTap: (){
                      print("踢人");
                      Get.to(()=>GroupUserView(userList: logic.groupDetailsData.users,))!.then((value) async{
                        print(value);
                        if(value!=null){
                          List<int> list = value;
                          list.forEach((element) {
                            logic.groupDetailsData.users!.forEach((element1) {
                              logic.outUser(element1.ryUserId,element1.remarkName);
                            });
                          });
                        }
                      });
                    }),
                  ):SizedBox(),),
                ),
              ),

              RongWidget.rowBaseWidget(
                  padding: EdgeInsets.all(15),
                  leftText: "群聊名称",
                  rightText: "${logic.groupDetailsData.groupName}",
                  // 管理员才能改群名
                  onTap:widget.groupType != 1? null:  (){
                    Get.dialog(
                      Center(
                        child: Material(
                          color: Colors.transparent,
                          child: ClipRRect(
                            child: Container(
                                width: Get.width * 0.6,
                                height: 140,
                                color: Colors.white,
                                padding: EdgeInsets.all(15),
                                child: Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      RongWidget.title("设置群名"),
                                      RongWidget.rongInput(
                                        controller: logic.textEditingControllerGroupName,
                                        circular: 5,
                                        hintText: "${'输入群备注名称'}",
                                      ),
                                      RongWidget.gradientButton("设置",onTap: (){
                                        Get.back();
                                        logic.setGroup();
                                      }),
                                    ],
                                  ),
                                )
                            ),
                            borderRadius: BorderRadius.circular(5),
                          ),
                        ),
                      ),
                    );
                  }
              ),

              RongWidget.rowBaseWidget(
                padding: EdgeInsets.all(15),
                leftText: "群聊二维码",
                onTap: ()=> Get.to(()=>GroupCodePage( groupDetailsData:logic.groupDetailsData )),
              ),

              RongWidget.rowBaseWidget(
                padding: EdgeInsets.all(15),
                leftText: "消息免打扰",
                right: FlutterSwitch(
                  height: 25,
                  width: 50,
                  toggleSize: 22.0,
                  padding: 0,
                  value: logic.disturb,
                  activeColor: Colors.green,
                  onToggle: (val) => logic.setDisturb(),
                ),
              ),

              RongWidget.rowBaseWidget(
                padding: EdgeInsets.all(15),
                leftText: "查找聊天内容",
                onTap: ()=> Get.to(()=>ChatRecordPage(targetId: logic.groupDetailsData.groupId,conversationType: 3,)),
              ),

              Builder(builder: (ctx){
                String name = "";
                logic.groupDetailsData.users!.forEach((element) {
                  if(element.ryUserId == getUserUtil().ryUserId){
                    name = element.remarkName ?? '';
                  }
                });
                return RongWidget.rowBaseWidget(
                  padding: EdgeInsets.all(15),
                  leftText: "我在本群的名称",
                  rightText: "$name",
                  onTap: (){
                    return;
                    Get.dialog(
                      Center(
                        child: Material(
                          color: Colors.transparent,
                          child: ClipRRect(
                            child: Container(
                                width: Get.width * 0.6,
                                height: 140,
                                color: Colors.white,
                                padding: EdgeInsets.all(15),
                                child: Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      RongWidget.title("设置我在本群的昵称"),
                                      RongWidget.rongInput(
                                        controller: logic.textEditingControllerUserName,
                                        circular: 5,
                                        hintText: "${'输入设置我在本群的昵称'}",
                                      ),
                                      RongWidget.gradientButton("设置",onTap: (){
                                        Get.back();
                                      }),
                                    ],
                                  ),
                                )
                            ),
                            borderRadius: BorderRadius.circular(5),
                          ),
                        ),
                      ),
                    );
                  },
                );
              }),

              InkWell(
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(15),
                  alignment: Alignment.center,
                  child: RongWidget.title("清空聊天记录",color: Colors.red,onTap: (){
                    logic.deleteMessages(widget.groupId,(v){
                      toast("清空成功");
                      Get.back();
                      Get.back();
                    },rcConversationType: 3);
                  }),
                ),
              ),

              Divider(height: 1,color: Colors.grey.shade100,),

              InkWell(
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(15),
                  alignment: Alignment.center,
                  child: RongWidget.title(widget.groupType == 1?"删除记录并解散群":"删除并退出群聊",color: Colors.red,onTap: (){
                    showDelOut();
                  }),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    Get.delete<ChatsSettingLogic>();
    super.dispose();
  }

  /// 退群、解散 弹出框
  showDelOut(){
    showDialog(context: context, builder: (ctx){
      return AlertDialog(
        title: Text("提示："),
        content: Text(widget.groupType == 1?"确定要解散该群聊吗？":"确定清空所有聊天记录并退出群聊吗？"),
        actions: <Widget>[
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop(false);
            },
          ),
          FlatButton(
            child: Text("确定"),
            onPressed: () {
              // 群主解散、群员退群
              if(widget.groupType == 1){
                logic.outGroup( );
              }else{
                logic.outUser(getUserUtil().ryUserId,getUserUtil().nikeName);
              }
            },
          ),
        ],
      );
    });
  }
}